package com.rightsidetech.http.log.parser;

import cn.hutool.extra.spring.SpringUtil;
import com.rightsidetech.commom.service.IService;
import com.rightsidetech.commom.utils.ReflectionUtils;
import com.rightsidetech.http.aspect.ModifyLog;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;

import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: yhr
 * @Date: 2021-11-12 14:22
 */
@Component
public class DefaultContentParse implements ContentParser{
    @Override
    public Object getResult(JoinPoint joinPoint, ModifyLog modifyLog) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object result = null;
        if ("GET".equals(request.getMethod())){
            result = getAllParameter(request).get(modifyLog.idField());
        }else {
            Object info = joinPoint.getArgs()[0];
            result = ReflectionUtils.getFieldValue(info, modifyLog.idField());
        }
        Assert.notNull(result,"未解析到id值，请检查前台传递参数是否正确");
        Class idType=modifyLog.idType();
        if(idType.equals(String.class)){
            Class cls=modifyLog.serviceClass();
            IService service = (IService) SpringUtil.getBean(cls);
            return  service.selectById(result.toString());
        }else  if(idType.equals(Long.class)) {
            Class cls=modifyLog.serviceClass();
            IService service = (IService) SpringUtil.getBean(cls);
            return  service.selectById(Long.valueOf(result.toString()));
        }else  if(idType.equals(List.class)) {
            Class cls=modifyLog.serviceClass();
            IService service = (IService) SpringUtil.getBean(cls);
            if (result instanceof List){
                return service.selectById(result);
            }else {
                List list = new ArrayList();
                list.add(result);
                return service.selectById(list);
            }
        }else {
            throw new RuntimeException("请核实id type");
        }
    }

    private Map<String,Object> getAllParameter(HttpServletRequest req) {

        Map<String, Object> map = new HashMap();
        Enumeration enums = req.getParameterNames();
        while (enums.hasMoreElements()) {
            String paramName = (String) enums.nextElement();

            String paramValue = req.getParameter(paramName);
            //形成键值对应的map
            map.put(paramName, paramValue);
        }
        return map;
    }
}
